using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;
using JGSY.CMS.LowCode.Platform.Infrastructure.Configuration.ServiceModules;
using JGSY.CMS.LowCode.Platform.Infrastructure.Authorization;

namespace JGSY.CMS.LowCode.Platform.Controllers
{
    /// <summary>
    /// 模块权限管理控制器
    /// 提供动态控制系统模块启用/禁用的API接口
    /// </summary>
    [ApiController]
    [Route("api/[controller]")]
    [RequirePermission("SYSTEM_ADMIN")] // 需要系统管理员权限
    public class ModulePermissionController : ControllerBase
    {
        private readonly ModulePermissionManager _permissionManager;
        private readonly ILogger<ModulePermissionController> _logger;

        public ModulePermissionController(
            ModulePermissionManager permissionManager,
            ILogger<ModulePermissionController> logger)
        {
            _permissionManager = permissionManager;
            _logger = logger;
        }

        /// <summary>
        /// 获取所有模块权限状态
        /// </summary>
        /// <returns>模块权限状态</returns>
        [HttpGet]
        public ActionResult<object> GetAllPermissions()
        {
            try
            {
                var permissions = _permissionManager.GetAllPermissions();
                return Ok(new
                {
                    Success = true,
                    Data = permissions,
                    Timestamp = DateTime.UtcNow
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取模块权限状态失败");
                return StatusCode(500, new
                {
                    Success = false,
                    Message = "获取模块权限状态失败",
                    Error = ex.Message
                });
            }
        }

        /// <summary>
        /// 获取特定服务模块权限状态
        /// </summary>
        /// <param name="permission">模块权限枚举</param>
        /// <returns>权限状态</returns>
        [HttpGet("service/{permission}")]
        public ActionResult<object> GetServiceModulePermission([FromRoute] ModulePermission permission)
        {
            try
            {
                var hasPermission = _permissionManager.HasServiceModulePermission(permission);
                return Ok(new
                {
                    Success = true,
                    Data = new
                    {
                        Permission = permission.ToString(),
                        Enabled = hasPermission,
                        Description = GetModuleDescription(permission)
                    }
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取服务模块权限失败: {Permission}", permission);
                return StatusCode(500, new
                {
                    Success = false,
                    Message = "获取服务模块权限失败",
                    Error = ex.Message
                });
            }
        }

        /// <summary>
        /// 获取特定中间件模块权限状态
        /// </summary>
        /// <param name="permission">中间件权限枚举</param>
        /// <returns>权限状态</returns>
        [HttpGet("middleware/{permission}")]
        public ActionResult<object> GetMiddlewarePermission([FromRoute] MiddlewarePermission permission)
        {
            try
            {
                var hasPermission = _permissionManager.HasMiddlewarePermission(permission);
                return Ok(new
                {
                    Success = true,
                    Data = new
                    {
                        Permission = permission.ToString(),
                        Enabled = hasPermission,
                        Description = GetMiddlewareDescription(permission)
                    }
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取中间件权限失败: {Permission}", permission);
                return StatusCode(500, new
                {
                    Success = false,
                    Message = "获取中间件权限失败",
                    Error = ex.Message
                });
            }
        }

        /// <summary>
        /// 设置服务模块权限
        /// </summary>
        /// <param name="permission">模块权限枚举</param>
        /// <param name="request">权限设置请求</param>
        /// <returns>设置结果</returns>
        [HttpPost("service/{permission}")]
        public ActionResult<object> SetServiceModulePermission(
            [FromRoute] ModulePermission permission,
            [FromBody] SetPermissionRequest request)
        {
            try
            {
                if (permission == ModulePermission.CoreServices)
                {
                    return BadRequest(new
                    {
                        Success = false,
                        Message = "核心服务模块不能被禁用"
                    });
                }

                _permissionManager.SetServiceModulePermission(permission, request.Enabled);

                _logger.LogInformation("管理员 {User} 将服务模块 {Permission} 设置为 {Status}", 
                    User.Identity?.Name, permission, request.Enabled ? "启用" : "禁用");

                return Ok(new
                {
                    Success = true,
                    Message = $"服务模块 {permission} 已{(request.Enabled ? "启用" : "禁用")}",
                    Data = new
                    {
                        Permission = permission.ToString(),
                        Enabled = request.Enabled,
                        UpdatedAt = DateTime.UtcNow,
                        Note = "⚠️ 注意: 模块权限更改需要重启应用程序才能生效"
                    }
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "设置服务模块权限失败: {Permission} -> {Enabled}", permission, request.Enabled);
                return StatusCode(500, new
                {
                    Success = false,
                    Message = "设置服务模块权限失败",
                    Error = ex.Message
                });
            }
        }

        /// <summary>
        /// 设置中间件权限
        /// </summary>
        /// <param name="permission">中间件权限枚举</param>
        /// <param name="request">权限设置请求</param>
        /// <returns>设置结果</returns>
        [HttpPost("middleware/{permission}")]
        public ActionResult<object> SetMiddlewarePermission(
            [FromRoute] MiddlewarePermission permission,
            [FromBody] SetPermissionRequest request)
        {
            try
            {
                if (permission == MiddlewarePermission.CoreMiddleware)
                {
                    return BadRequest(new
                    {
                        Success = false,
                        Message = "核心中间件不能被禁用"
                    });
                }

                _permissionManager.SetMiddlewarePermission(permission, request.Enabled);

                _logger.LogInformation("管理员 {User} 将中间件 {Permission} 设置为 {Status}", 
                    User.Identity?.Name, permission, request.Enabled ? "启用" : "禁用");

                return Ok(new
                {
                    Success = true,
                    Message = $"中间件 {permission} 已{(request.Enabled ? "启用" : "禁用")}",
                    Data = new
                    {
                        Permission = permission.ToString(),
                        Enabled = request.Enabled,
                        UpdatedAt = DateTime.UtcNow,
                        Note = "⚠️ 注意: 中间件权限更改需要重启应用程序才能生效"
                    }
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "设置中间件权限失败: {Permission} -> {Enabled}", permission, request.Enabled);
                return StatusCode(500, new
                {
                    Success = false,
                    Message = "设置中间件权限失败",
                    Error = ex.Message
                });
            }
        }

        /// <summary>
        /// 批量设置模块权限
        /// </summary>
        /// <param name="request">批量权限设置请求</param>
        /// <returns>设置结果</returns>
        [HttpPost("batch")]
        public ActionResult<object> SetBatchPermissions([FromBody] BatchPermissionRequest request)
        {
            var results = new List<object>();
            var errors = new List<string>();

            try
            {
                // 处理服务模块权限
                if (request.ServiceModules != null)
                {
                    foreach (var item in request.ServiceModules)
                    {
                        try
                        {
                            if (Enum.TryParse<ModulePermission>(item.Key, out var permission))
                            {
                                if (permission != ModulePermission.CoreServices)
                                {
                                    _permissionManager.SetServiceModulePermission(permission, item.Value);
                                    results.Add(new { Type = "Service", Permission = item.Key, Enabled = item.Value, Status = "Success" });
                                }
                                else
                                {
                                    errors.Add($"核心服务模块 {item.Key} 不能被禁用");
                                }
                            }
                            else
                            {
                                errors.Add($"无效的服务模块权限: {item.Key}");
                            }
                        }
                        catch (Exception ex)
                        {
                            errors.Add($"设置服务模块 {item.Key} 失败: {ex.Message}");
                        }
                    }
                }

                // 处理中间件权限
                if (request.MiddlewareModules != null)
                {
                    foreach (var item in request.MiddlewareModules)
                    {
                        try
                        {
                            if (Enum.TryParse<MiddlewarePermission>(item.Key, out var permission))
                            {
                                if (permission != MiddlewarePermission.CoreMiddleware)
                                {
                                    _permissionManager.SetMiddlewarePermission(permission, item.Value);
                                    results.Add(new { Type = "Middleware", Permission = item.Key, Enabled = item.Value, Status = "Success" });
                                }
                                else
                                {
                                    errors.Add($"核心中间件 {item.Key} 不能被禁用");
                                }
                            }
                            else
                            {
                                errors.Add($"无效的中间件权限: {item.Key}");
                            }
                        }
                        catch (Exception ex)
                        {
                            errors.Add($"设置中间件 {item.Key} 失败: {ex.Message}");
                        }
                    }
                }

                return Ok(new
                {
                    Success = errors.Count == 0,
                    Message = $"批量权限设置完成，成功 {results.Count} 项，失败 {errors.Count} 项",
                    Data = new
                    {
                        Results = results,
                        Errors = errors,
                        UpdatedAt = DateTime.UtcNow
                    }
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "批量设置模块权限失败");
                return StatusCode(500, new
                {
                    Success = false,
                    Message = "批量设置模块权限失败",
                    Error = ex.Message
                });
            }
        }

        /// <summary>
        /// 获取模块描述
        /// </summary>
        private string GetModuleDescription(ModulePermission permission)
        {
            return permission switch
            {
                ModulePermission.LoggingServices => "日志服务模块 - 系统日志、结构化日志、性能日志",
                ModulePermission.AuthenticationServices => "认证授权服务模块 - JWT认证、角色权限、安全策略",
                ModulePermission.CacheServices => "缓存服务模块 - 内存缓存、分布式缓存、智能缓存策略",
                ModulePermission.DatabaseServices => "数据库服务模块 - EF Core、仓储模式、多数据库支持",
                ModulePermission.PerformanceServices => "性能优化服务模块 - 性能监控、查询优化、智能预热",
                ModulePermission.ApplicationServices => "应用业务服务模块 - 业务逻辑服务、领域服务",
                ModulePermission.SystemOptimizationServices => "系统优化服务模块 - 系统级性能优化、资源管理",
                ModulePermission.SwaggerServices => "API文档服务模块 - Swagger文档生成、API测试界面",
                ModulePermission.AdvancedMonitoringServices => "高级监控服务模块 - 实时监控、性能分析、告警系统",
                ModulePermission.MultiTenantAdvancedServices => "多租户高级功能模块 - 租户隔离、资源配额、数据迁移",
                _ => "未知模块"
            };
        }

        /// <summary>
        /// 获取中间件描述
        /// </summary>
        private string GetMiddlewareDescription(MiddlewarePermission permission)
        {
            return permission switch
            {
                MiddlewarePermission.PerformanceMiddleware => "性能优化中间件 - 响应时间监控、缓存控制",
                MiddlewarePermission.LoggingMiddleware => "日志中间件 - 请求日志、操作审计、安全日志",
                MiddlewarePermission.AuthenticationMiddleware => "认证授权中间件 - 身份验证、权限检查",
                MiddlewarePermission.RoutingMiddleware => "路由中间件 - 控制器路由、API路由映射",
                MiddlewarePermission.SystemOptimizationMiddleware => "系统优化中间件 - 响应压缩、静态文件缓存",
                MiddlewarePermission.SwaggerMiddleware => "Swagger中间件 - API文档界面、交互式测试",
                MiddlewarePermission.SecurityMiddleware => "安全中间件 - CORS、CSRF防护、安全头设置",
                _ => "未知中间件"
            };
        }
    }

    /// <summary>
    /// 权限设置请求模型
    /// </summary>
    public class SetPermissionRequest
    {
        /// <summary>
        /// 是否启用
        /// </summary>
        public bool Enabled { get; set; }

        /// <summary>
        /// 设置原因（可选）
        /// </summary>
        public string? Reason { get; set; }
    }

    /// <summary>
    /// 批量权限设置请求模型
    /// </summary>
    public class BatchPermissionRequest
    {
        /// <summary>
        /// 服务模块权限设置
        /// </summary>
        public Dictionary<string, bool>? ServiceModules { get; set; }

        /// <summary>
        /// 中间件权限设置
        /// </summary>
        public Dictionary<string, bool>? MiddlewareModules { get; set; }

        /// <summary>
        /// 操作原因（可选）
        /// </summary>
        public string? Reason { get; set; }
    }
}
